import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('user') || '{}'))
  const isLoggedIn = ref(!!token.value)

  // 设置登录状态
  const setLoginState = (tokenValue, user) => {
    token.value = tokenValue
    userInfo.value = user
    isLoggedIn.value = true
    
    // 保存到本地存储
    localStorage.setItem('token', tokenValue)
    localStorage.setItem('user', JSON.stringify(user))
  }

  // 清除登录状态
  const clearLoginState = () => {
    token.value = ''
    userInfo.value = {}
    isLoggedIn.value = false
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setLoginState,
    clearLoginState
  }
}) 